<template>
  <div style="height: 100%">
    <!-- 头部 -->
    <div class="page-header">
      <div class="search-wrapper">
        <el-form :model="searchForm" :inline="true">
          <el-form-item>
            <el-input clearable v-model="searchForm.name" placeholder="请输入查询用户名称"></el-input>
          </el-form-item>
          <el-form-item>
            <el-cascader v-model="searchForm.city" :options="cityList" placeholder="请选择查询城市" clearable
              :props="{ expandTrigger: 'hover', label: 'name', value: 'id' }">
            </el-cascader>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchEvent">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-button v-if="identity != 4" type="primary" plain class="addUser" @click="addUserModel">添加用户</el-button>
    </div>

    <!-- 列表 -->
    <div class="page-list" v-loading="loading">
      <el-table height="100%" :data="tableData" stripe style="width: 100%">
        <el-table-column prop="" label="" width="30"> </el-table-column>
        <el-table-column prop="" label="用户">
          <template slot-scope="scope">
            <div class="name-avatar">
              <img class="avatar-itme" :src="scope.row.image" />
              <div class="name-item">{{ scope.row.name }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号"> </el-table-column>
        <el-table-column prop="" label="归属城市">
          <template slot-scope="scope">
            {{ scope.row.area }}
          </template>
        </el-table-column>
        <el-table-column v-if="identity == 3" prop="brand_name" label="品牌">
        </el-table-column>
        <el-table-column v-if="identity == 1 || identity == 2" prop="position" label="职务">
        </el-table-column>
        <el-table-column prop="role_name" label="角色权限" v-if="identity != 4"> </el-table-column>
        <el-table-column prop="updated_at" label="更新时间"> </el-table-column>
        <el-table-column prop="" label="操作" width="150">
          <template slot-scope="scope">
            <div class="btn-group">
              <div class="btn-item">
                <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                  <i class="el-icon-edit-outline" @click="editEven(scope.row, 'admin_updateAdmin')"></i>
                </el-tooltip>
              </div>
              <div class="btn-item">
                <el-tooltip class="item" effect="dark" content="删除" placement="top">
                  <i class="el-icon-delete" @click="editEven(scope.row, 'admin_deleteAdmin')"></i>
                </el-tooltip>
              </div>
              <div class="btn-item" v-if="scope.row.login_fail_num >= 3">
                <el-tooltip class="item" effect="dark" content="解除登录限制" placement="top">
                  <i class="el-icon-link" @click="editEven(scope.row, 'removeLoginRestrictions')"></i>
                </el-tooltip>
              </div>
              <!-- <div v-if="gather.length == 0">-</div> -->
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="page-footer">
      <el-pagination background layout="prev, pager, next" :page-size="num" :current-page.sync="page" :total="total"
        @current-change="pageChange">
      </el-pagination>
    </div>

    <!-- 弹窗 -->
    <el-dialog :title="userFormType == 'add' ? '添加用户' : '修改用户'" :visible.sync="dialogFormVisible" @close="saveUserClose"
      :close-on-click-modal="false" width="460px">
      <el-form :model="userForm" :rules="userRules" class="user-info" ref="userFrom" label-width="80px"
        label-position="left">
        <el-form-item label="用户头像" prop="imgUrl">
          <el-upload action="#" list-type="picture-card" :show-file-list="false" :on-change="change_file"
            accept=".png,.jpeg,.jpg,.webp" :auto-upload="false">
            <img v-if="userForm.imgUrl" :src="userForm.imgUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名称" prop="name">
          <el-input clearable maxlength="10" v-model="userForm.name" placeholder="请输入用户名称"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input clearable v-model="userForm.phone" type="number"
            oninput="if(value.length > 11) value=value.slice(0, 11)" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="userFormType == 'add'">
          <el-input clearable v-model="userForm.password" placeholder="请输入登录密码" show-password></el-input>
        </el-form-item>
        <el-form-item label="所属城市" prop="city">
          <el-cascader v-model="userForm.city" :options="cityList" placeholder="请选择所属城市" clearable
            :props="{ expandTrigger: 'hover', label: 'name', value: 'id' }">
          </el-cascader>
        </el-form-item>
        <el-form-item v-if="userInfo.position_id == 1 && userForm.position_id == 2" label="优惠比例" prop="discount_ratio">
          <el-input clearable v-model="userForm.discount_ratio" placeholder="请输入优惠比例（0%~100%）">
            <span slot="suffix">%</span>
          </el-input>
        </el-form-item>
        <el-form-item label="职务" prop="position_id" v-if="identity == 1 || identity == 2">
          <el-select @change="positionChange" clearable v-model="userForm.position_id" placeholder="请选择职务">
            <el-option v-for="item in organizationList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌" prop="brand_id" v-if="identity == 3 || identity == 4">
          <el-select clearable v-model="userForm.brand_id" placeholder="请选择品牌">
            <el-option v-for="item in brandList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工程监理" v-if="identity == 2 && userForm.position_id == 7" prop="engineering_supervision_id">
          <el-select clearable v-model="userForm.engineering_supervision_id" placeholder="请选择工程监理">
            <el-option v-for="item in engineeringSupervisionList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role_id" v-if="identity != 4">
          <el-select clearable v-model="userForm.role_id" placeholder="请选择角色">
            <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveUserClose">取 消</el-button>
        <el-button type="primary" @click="saveSubmit" :loading="submitBtn">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import permissionApi from "@/api/permissionApi";
  import adminApi from "@/api/adminApi";
  import commonApi from "@/api/common";
  import brandApi from "@/api/brandApi";
  import {
    getUserInfo
  } from "@/utils/auth";

  export default {
    name: "",
    props: ["identity", "engineeringSupervisionList"],
    data() {
      var password = (rule, value, callback) => {
        if (!value) {
          return callback(new Error("密码不能为空"));
        } else if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/.test(value)) {
          callback(new Error("密码须8-16位,包含大小写字母、数字"));
        } else {
          callback();
        }
      };
      return {
        loading: false,
        // 城市数据
        cityList: [],
        roleList: [],

        // 用户列表数据
        page: 1,
        num: 10,
        total: 0,
        tableData: [],

        // 查询数据'
        searchForm: {
          name: "",
          city: [],
        },
        // 操作用户
        dialogFormVisible: false,
        userRelationList: [],
        userFormType: "add",
        userForm: {
          admin_id: "",
          name: "",
          imgUrl: "",
          imgFile: null,
          phone: "",
          password: "",
          position_id: "",
          brand_id: "",
          role_id: "",
          city: [],
          discount_ratio: "",
          engineering_supervision_id: ''
        },
        userRules: {
          imgUrl: [{
            required: true,
            message: "请上传头像",
            trigger: "change"
          }],
          name: [{
            required: true,
            message: "请输入用户名称",
            trigger: "change"
          }, ],
          phone: [{
              required: true,
              message: "请输入手机号",
              trigger: "change"
            },
            {
              min: 11,
              message: "长度至少11个字符",
              trigger: "blur"
            },
          ],
          password: [{
            validator: password,
            required: true,
            trigger: "change"
          }],
          city: [{
            required: true,
            message: "请选择所属城市",
            trigger: "change"
          }, ],
          role_id: [{
            required: true,
            message: "请选择角色",
            trigger: "change"
          }],
        },
        submitBtn: false,
        organizationList: [], //组织架构列表
        brandList: [], //品牌列表
        userInfo: {}, //用户信息
      };
    },
    watch: {
      // "userForm.position_id": (newVal, oldVal) => {
      //   console.log(newVal, oldVal, "newVal, oldVal")
      //   if (newVal == 7) {
      //     this.userRules.engineering_supervision_id = [{
      //       required: true,
      //       message: "请选择工程监理",
      //       trigger: "change"
      //     }]
      //   } else {
      //     delete this.userRules.engineering_supervision_id;
      //   }
      // }
    },
    mounted() {
      this.userInfo = getUserInfo();
      this.getAdminList();
      this.getRoleList();
      this.getAreaList();
      switch (this.identity) {
        case 1: //企业人员
          this.userRules.position_id = [{
            required: true,
            message: "请选择职务",
            trigger: "change"
          }, ];
          this.getOrganizationList();
          break;
        case 2: //施工方
          this.userRules.position_id = [{
            required: true,
            message: "请选择职务",
            trigger: "change"
          }, ];
          this.getOrganizationList();
          break;
        case 3: //品牌方
          this.userRules.brand_id = [{
            required: true,
            message: "请选择品牌",
            trigger: "change"
          }, ];
          this.getBrandList();
          break;
        case 4: //普通用户
          this.getBrandList();
          break;
        default:
      }
    },
    methods: {
      getAdminList() {
        let that = this;
        var obj = {
          page: this.page,
          num: this.num,
          keyword: this.searchForm.name,
          province_id: this.searchForm.city.length ? this.searchForm.city[0] : "",
          city_id: this.searchForm.city.length ? this.searchForm.city[1] : "",
          county_id: this.searchForm.city.length ? this.searchForm.city[2] : "",
          identity: this.identity,
        };
        this.loading = true;
        adminApi
          .getAdminList(obj)
          .then((res) => {
            console.log(res, "用户列表");
            this.loading = false;
            if (res.code == 200) {
              that.tableData = res.data.list;
              that.total = res.data.max;
            } else {
              if (res.message == "暂无数据") {
                if (this.page == 1) {
                  that.tableData = [];
                }
                return;
              }
              this.$message({
                message: res.message,
                type: "warning",
              });
              that.tableData = [];
              that.total = 0;
            }
          })
          .catch((err) => {
            this.loading = false;
            this.$message({
              message: err.message,
              type: "warning",
            });
          });
      },
      searchEvent() {
        this.page = 1;
        this.getAdminList();
      },
      pageChange(page) {
        this.page = page;
        this.getAdminList();
      },

      // 操作用户弹窗 - 头像数据
      change_file(e) {
        this.userForm.imgUrl = e.url;
        this.userForm.imgFile = e.raw;
      },
      addUserModel() {
        let that = this;
        this.userFormType = "add";
        this.dialogFormVisible = true;
        this.$nextTick(() => {
          // this.$refs.userFrom.resetFields();
          this.$refs.userFrom.clearValidate();
        });
      },
      saveUserClose() {
        this.userForm = {
          admin_id: "",
          name: "",
          imgUrl: "",
          imgFile: null,
          phone: "",
          password: "",
          position_id: "",
          brand_id: "",
          role_id: "",
          city: [],
          discount_ratio: "",
          engineering_supervision_id: ''
        };
        this.$nextTick(() => {
          // this.$refs.userFrom.resetFields();
          this.$refs.userFrom.clearValidate();
          this.dialogFormVisible = false;
        });
      },
      // 操作用户弹窗 - 提交
      saveSubmit() {
        //平台用户关联
        let userForm = this.userForm;
        console.log(userForm, "参数");
        this.$refs.userFrom.validate((valid) => {
          if (valid) {
            if (userForm.discount_ratio) {
              var reg = /^(?:100(?:\.0{1,2})?|[1-9]?\d(?:\.\d{1,2})?)$/;
              if (!reg.test(userForm.discount_ratio)) {
                this.$message.warning("请输入0-100的数值");
                return;
              }
            }
            let formdata = new FormData();
            formdata.append("identity", this.identity);
            formdata.append("engineering_supervision_id", userForm.engineering_supervision_id);
            formdata.append("image", userForm.imgFile || "");
            formdata.append("name", userForm.name);
            formdata.append("phone", userForm.phone);
            formdata.append("password", userForm.password);
            formdata.append("province_id", userForm.city[0]);
            formdata.append("city_id", userForm.city[1]);
            formdata.append("county_id", userForm.city[2]);
            formdata.append("role_id", userForm.role_id);
            formdata.append("position_id", userForm.position_id || 0);
            formdata.append("brand_id", userForm.brand_id || 0);
            formdata.append("admin_id", userForm.admin_id);
            formdata.append("discount_ratio", userForm.imgFile || 0);
            this.submitBtn = true;
            if (this.userFormType == "add") {
              this.addAdmin(formdata);
            } else {
              this.updateAdmin(formdata);
            }
          } else {
            return false;
          }
        });
      },
      addAdmin(userForm) {
        adminApi
          .addAdmin(userForm)
          .then((res) => {
            console.log(res, "addAdmin");
            if (res.code == 200) {
              this.saveUserClose();
              this.getAdminList();
              this.$message({
                type: "success",
                message: "添加成功!",
              });
            } else {
              this.$message.error(res.message);
            }
            this.submitBtn = false;
          })
          .catch((err) => {
            this.submitBtn = false;
            this.$message.error(err.message);
          });
      },
      updateAdmin(userForm) {
        adminApi
          .updAdmin(userForm)
          .then((res) => {
            console.log(res, "updateAdmin");
            if (res.code == 200) {
              this.saveUserClose();
              this.getAdminList();
              this.$message({
                type: "success",
                message: "修改成功!",
              });
            } else {
              this.$message.error(res.message);
            }
            this.submitBtn = false;
          })
          .catch((err) => {
            this.submitBtn = false;
            this.$message.error(err.message);
          });
      },
      //操作事件
      editEven(row, item) {
        switch (item) {
          case "admin_updateAdmin":
            this.saveUser(row);
            break;
          case "admin_deleteAdmin":
            this.delUser(row);
            break;
          case "removeLoginRestrictions":
            this.removeLoginRestrictions(row);
            break;
          default:
        }
      },
      // 解除登录限制
      removeLoginRestrictions(row) {
        this.$confirm('此操作将解除该用户登录限制, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          adminApi.removeLoginRestrictions({
            admin_id: row.id
          }).then(res => {
            console.log(res, "解除登录限制")
            if (res.code == 200) {
              this.$message.success('操作成功')
              this.getAdminList();
            } else {
              this.$message.warning(res.message)
            }
          }).catch((err) => {
            this.$message.warning(err.message);
          })
        }).catch(() => {

        });
      },
      // 编辑用户
      saveUser(row) {
        console.log(row, "saveUser");
        this.userForm.admin_id = row.id;
        this.userForm.name = row.name;
        this.userForm.imgUrl = row.image;
        this.userForm.phone = row.phone;
        this.userForm.city = [row.province_id, row.city_id, row.county_id];
        this.userForm.role_id = row.role_id == 0 ? "" : row.role_id;
        this.userForm.brand_id = row.brand_id == 0 ? "" : row.brand_id;
        this.userForm.position_id = row.position_id == 0 ? "" : row.position_id;
        this.userForm.discount_ratio = row.discount_ratio;
        this.userForm.engineering_supervision_id = row.engineering_supervision_id == 0 ? '' : row
          .engineering_supervision_id;
        this.userFormType = "edit";
        this.dialogFormVisible = true;
        this.$nextTick(() => {
          this.$refs.userFrom.clearValidate();
        });
      },
      // 删除用户
      delUser(row) {
        this.$confirm('是否删除 "' + row.name + '" 用户?', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          adminApi
            .delAdmin({
              admin_id: row.id,
            })
            .then((res) => {
              if (res.code == 200) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.getAdminList();
              } else {
                this.$message.error(res.message);
              }
            });
        });
      },
      // 获取角色列表
      getRoleList() {
        permissionApi
          .getRoleList({
            page: 1,
            num: 999,
          })
          .then((res) => {
            console.log(res, "角色列表");
            if (res.code == 200) {
              this.roleList = res.data.list;
            }
          });
      },
      // 省市区
      getAreaList() {
        commonApi.getAreaList().then((res) => {
          console.log(res, "省市区");
          if (res.code == 200) {
            this.cityList = res.data;
          }
        });
      },
      // 组织架构列表
      getOrganizationList() {
        adminApi
          .getOrganizationList({
            type: this.identity == 2 ? 1 : 2,
          })
          .then((res) => {
            console.log(res, "组织架构列表");
            if (res.code == 200) {
              this.organizationList = res.data;
            }
          });
      },
      // 品牌列表
      getBrandList() {
        brandApi
          .getBrandList({
            page: 1,
            num: 999,
          })
          .then((res) => {
            console.log(res, "品牌列表");
            if (res.code == 200) {
              this.brandList = res.data.list;
            }
          });
      },
      // 单文件上传
      uploadFile(data) {
        return new Promise((resolve, reject) => {
          commonApi.uploadFile(data).then((res) => {
            // console.log(res, "单文件上传");
            resolve(res);
          });
        });
      },
      // 职位筛选
      positionChange(e) {
        this.userForm.engineering_supervision_id = '';
        if (e == 7) {
          this.userRules.engineering_supervision_id = [{
            required: true,
            message: "请选择工程监理",
            trigger: "change"
          }]
        } else {
          delete this.userRules.engineering_supervision_id;
        }
        this.$nextTick(() => {
          this.$refs.userFrom.clearValidate();
        })
      },
    },
  };

</script>

<style lang="scss" src="./index.scss" scoped></style>
